<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\BaseController;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;
use Psr\Http\Message\StreamInterface;

class WechatController extends BaseController
{
    protected Client $client;

    public function __construct()
    {
        $this->client = new Client;
    }

    public function serve()
    {
        $server = app('easywechat.official_account')->getServer();

        $server->with(function($message){
            return "欢迎关注！";
        });

        return $server->serve();
    }

    public function getAccessToken($tenantId = null )
    {
        $config = config('easywechat.official_account.default');

        $token_cache = json_decode(Redis::get('accessToken-'.$tenantId),true);

        if ($token_cache && $token_cache['access_token'] && $token_cache['expire_time'] > time()){
            return $token_cache['access_token'];
        }else{
            $appid = $config['app_id'];
            $secret = $config['secret'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            try {
                $response = $this->client->get($url,['query'=>[
                    'grant_type'=>'client_credential',
                    'appid'=>$appid,
                    'secret'=>$secret
                ]]);
                $res = json_decode($response->getBody());
                $wechat_token['access_token'] = $res->access_token;
                $wechat_token['expire_time'] = time() + 7000;
                Redis::set('accessToken-'.$tenantId,json_encode($wechat_token));
                return $res->access_token;
            }catch (GuzzleException $e) {
                return $e->getMessage();
            }
        }

    }

    public function getWxMenu(Request $request): StreamInterface|string
    {
        $user = $request->get('userInfo');
        $tenantId = $user['tenantId'];
        $token = $this->getAccessToken($tenantId);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/get';
        try {
            $response = $this->client->get($url,['query'=>[
                'access_token'=>$token
            ]]);
            return $response->getBody();
        } catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }

    public function addWxMenu(Request $request): StreamInterface|string
    {
        $menus = $request->input();
        $token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create';
        try {
            $response = $this->client->post($url,[
                'body'=>json_encode($menus,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                'query'=>[
                    'access_token'=>$token
                ]
            ]);
            return $response->getBody();
        }catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }

    public function getMaterialList(Request $request): StreamInterface|string
    {
        $type = $request->input('type');
        $token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=' . $token;
        try {
            $response = $this->client->post($url,['json'=>[
                    'type'=>$type,
                    'offset'=>'0',
                    'count'=>'3']]
            );
            return $response->getBody();
        } catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }

    public function getMaterial(Request $request): StreamInterface|string
    {
        $id = $request->input('id');
        $token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$token;
        try {
            $response = $this->client->post($url,['json'=>['media_id'=>$id]]);
            return $response->getBody();
        } catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }
}
